<!--  -->
<template>
  <div class="Shopcar container">
    <!-- 购物车头部 -->
    <div class="cart-header">
      <div class="cart-header-content">
        <p>
          <i class="el-icon-shopping-cart-full" style="color: #ff6700; font-weight: 600">
          </i>
          购物车
        </p>
        <span>喜欢就赶快下单吧</span>
      </div>
    </div>
    <div class="content" v-if="shoppingCart.length > 0">
      <ul>
        <!-- 购物车表头 -->
        <li class="header">
          <div class="pro-check">
            <el-checkbox v-model="isAllCheck" @change="changeCheck">全选</el-checkbox>
          </div>
          <div class="pro-img"></div>
          <div class="pro-name">商品名称</div>
          <div class="pro-price">单价</div>
          <div class="pro-num">数量</div>
          <div class="pro-total">小计</div>
          <div class="pro-action">操作</div>
        </li>
        <!-- 购物车表头END -->

        <!-- 购物车列表 -->
        <li class="product-list" v-for="(item, index) in shoppingCart" :key="item.id">
          <div class="pro-check">
            <el-checkbox :value="item.check" @change="handelCheck(item.id)">
            </el-checkbox>
          </div>
          <div class="pro-img">
            <router-link :to="{ path: '/details', query: { id: item.proid } }">
              <img :src="item.skuImg" class="pro-img-img" />
            </router-link>
          </div>
          <div class="pro-name">
            {{ item.skuName }}
            <!-- <router-link>{{item.productName}}</router-link> -->
          </div>
          <div class="pro-price">{{ item.price }}元</div>
          <div class="pro-num">
            <el-input-number
              size="small"
              v-model="item.count"
              :key="index"
              @change="handleChange($event, index, item.id)"
              :min="1"
            ></el-input-number>
          </div>
          <div class="pro-total pro-total-in">{{ item.price * item.count }}元</div>
          <div class="pro-action">
            <el-popover placement="right">
              <p>确定删除吗？</p>
              <div style="text-align: right; margin: 10px 0 0">
                <el-button type="primary" size="mini" @click="deleteCart(item.id)"
                  >确定</el-button
                >
              </div>
              <i class="el-icon-error" slot="reference" style="font-size: 18px"></i>
            </el-popover>
          </div>
        </li>
        <!-- 购物车列表END -->
      </ul>
      <div style="height: 20px"></div>
      <!-- 购物车底部导航条 -->
      <div class="cart-bar">
        <div class="cart-bar-left">
          <span>
            <router-link to="/home">继续购物</router-link>
            <!-- <router-link ></router-link> -->
          </span>
          <span class="sep">|</span>
          <span class="cart-total">
            <!-- <span class="cart-total-num">{{totalNum}}</span> 件商品， -->
            已选择
            <span class="cart-total-num">{{ totalNum }}</span> 件
          </span>
        </div>
        <div class="cart-bar-right">
          <span>
            <span class="total-price-title">合计：</span>
            <span class="total-price">{{ totalPrice }}</span>
          </span>
          <div @click="goBuy">去结算</div>
          <!-- <router-link>
            
          </router-link> -->
        </div>
      </div>
      <!-- 购物车底部导航条END -->
    </div>
    <!-- 购物车主要内容区END -->

    <!-- 购物车为空的时候显示的内容 -->
    <div v-else class="cart-empty">
      <div class="empty">
        <h2>您的购物车还是空的！</h2>
        <p>快去购物吧！</p>
      </div>
    </div>
    <!-- 购物车为空的时候显示的内容END -->
  </div>
</template>

<script>
// import func from 'vue-editor-bridge';
import cookie from "js-cookie";
export default {
  name: "Shopcar",
  data() {
    return {
      isAllCheck: true,
      // 总价格
      totalNum: 0,
      // 总数量
      totalPrice: 0,
      shoppingCart: [],
      buyGoodsList: [],
    };
  },
  created() {
    // if (cookie.get("shopingCart")) {
    //   console.log("shopingCart", this.shoppingCart);
    //   this.shoppingCart = cookie.get("shopingCart");
    // } else {
    this.getShoppingCart();
    this.isAllCheck = true;
    //   cookie.set("isAllCheck", this.isAllCheck, { domain: "localhost" });
    // }
  },
  methods: {
    async getShoppingCart() {
      const { data: res } = await this.$http.get("/dqxmall/cart/list");
      if (res.code !== 0) return this.$message.error("购物车列表获取失败");
      console.log("gouwuche", res);
      this.$store.dispatch("setShopcarNumber", res.cartVOS.length);
      cookie.set("shopcarNumber", res.cartVOS.length, { domain: "localhost" });
      this.shoppingCart = [];
      res.cartVOS.forEach((item) => {
        var data = {};
        (data.skuid = item.skuid),
          (data.id = item.id),
          (data.skuName = item.skuName),
          (data.skuImg = item.skuImg),
          (data.stockCount = item.stockCount),
          (data.saleCount = item.saleCount),
          (data.price = item.price),
          (data.count = item.count);
        (data.proid = item.proid), (data.userid = item.userid);
        data.check = true;
        this.shoppingCart.push(data);
      });
      // console.log(this.shoppingCart);
      this.setCarInfo(this.shoppingCart);
    },
    // 复选框
    handelCheck(id) {
      console.log(id);
      this.shoppingCart.forEach((item) => {
        if (item.id === id) {
          item.check = !item.check;
        }
      });
      // console.log("sssssss", this.shoppingCart);
      this.setCarInfo(this.shoppingCart);
    },
    // 全选功能
    changeCheck(val) {
      // console.log(this.shoppingCart);
      this.shoppingCart.forEach((item) => {
        item.check = val;
      });
      this.setCarInfo(this.shoppingCart);
    },
    // 设置购物车状态
    setCarInfo(cartInfo) {
      this.isAllCheck = true;
      this.totalNum = 0;
      this.totalPrice = 0;
      cartInfo.forEach((item) => {
        if (item.check) {
          this.totalPrice += item.price * item.count;
          this.totalNum += 1;
        } else {
          this.isAllCheck = false;
        }
      });
      // cookie.set("shopingCart", JSON.stringify(this.shoppingCart), {
      //   domain: "localhost",
      // });
      // console.log("cxcx", JSON.parse(cookie.get("shopingCart")));
    },
    // 修改商品数量的时候调用该函数
    handleChange(currentValue, key, id) {
      // 当修改数量时，默认勾选
      this.shoppingCart[key].check = true;
      if (this.shoppingCart[key].count <= this.shoppingCart[key].stockCount) {
        // this.updateShoppingCart({ key: key, prop: "check", val: true });
        // console.log("skud", currentValue, key, id);
        // this.shoppingCart[key].count += currentValue;
        // console.log(this.shoppingCart[key].count);
        // 向后端发起更新购物车的数据库信息请求
        this.$http
          .post("/dqxmall/cart/update", {
            id: this.shoppingCart[key].id,
            count: this.shoppingCart[key].count,
          })
          .then((res) => {
            // console.log("数量更新", res);
            if (res.data.code !== 0) return this.$message.error("数量更新失败");
            // this.getShoppingCart();
            this.setCarInfo(this.shoppingCart);
          });
      } else {
        this.$message.error("库存不足");
      }
    },
    // 删除购物车
    async deleteCart(id) {
      // console.log("shanchu", id);
      const { data: res } = await this.$http.post("/dqxmall/cart/delete", [id]);
      // console.log(res);
      if (res.code !== 0) this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getShoppingCart();
    },
    // 去结算
    goBuy() {
      if (this.totalNum <= 0) {
        return this.$message.error("请先选择购买的商品");
      }
      //获取选中的商品
      this.shoppingCart.forEach((item) => {
        if (item.check) {
          this.buyGoodsList.push(item);
        }
      });
      console.log("DD", this.buyGoodsList);
      this.$store.dispatch("setBuyGoodsList", this.buyGoodsList);
      this.$store.dispatch("setTotalPrice", this.totalPrice);
      this.$router.push({ path: "/purchase" });
    },
  },
};
</script>
<style lang="less" scoped>
@import "../assets/css/total.less";
.Shopcar {
  .cart-header {
    box-sizing: border-box;
    .cart-header-content {
      display: flex;
      border-bottom: 2px solid rgb(255, 102, 0);
      p {
        height: 50px;
        width: 170px;
        font-size: 25px;
        margin: 20px 10px;
      }
      span {
        font-size: 15px;
        color: rgb(128, 123, 123);
        padding: 40px 0 0 0;
      }
    }
  }
  .content {
    box-sizing: border-box;
    li {
      border-bottom: 1px solid rgb(138, 137, 137);
    }
    .header,
    .product-list {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 120px;
      .pro-check,
      .pro-img,
      .pro-total,
      .pro-action {
        width: 120px;
        text-align: center;
        .pro-img-img {
          height: 100%;
          width: 100%;
        }
      }
      .pro-name {
        width: 370px;
      }
      .pro-price,
      .pro-num {
        width: 180px;
        text-align: center;
      }
    }
    .cart-bar {
      height: 60px;
      .cart-bar-left {
        text-align: center;
        float: left;
        margin-bottom: 20px;
        span {
          height: 50px;
          width: 100px;
          padding-left: 30px;
        }
        .sep {
          margin: 0 10px;
        }

        .cart-total {
          .cart-total-num {
            color: rgb(255, 123, 0);
          }
        }
      }
      .cart-bar-right {
        float: right;
        display: flex;
        span {
          .total-price-title {
            width: 200px;
            font-size: 15px;
            color: rgb(255, 123, 0);
          }
          .total-price {
            font-size: 25px;
          }
        }
        div {
          color: white;
          width: 200px;
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 10px;
          margin: 0 20px;
          cursor: pointer;
          background-color: rgb(255, 123, 0);
        }
      }
    }
  }
}
</style>
